import { Button, Message, Result } from '@arco-design/web-react';
import QRCodeImg from '@src/components/QRCodeImg';
import DetailModal from '@src/components/detailModal';
import LoadingMask from '@src/components/loadingMask';
import { useEffect, useRef, useState } from 'react';
import { apiCreatePay, apiQueryPayStatus } from '../api';

interface Props {
  onClose: (update?: boolean) => void;
  show: boolean;
}

// 等待支付
const payWait = 'waiting_pay';
// 支付超时
const payTimeOut = 'closed';
// 支付失败
const payError = 'error';
// 支付成功
const paySuccess = 'success_pay';
/// 充值选项
const rechargeItems = [100, 300, 500, 1000, 2000, 5000];
export default function AccountRechargeDialog({ onClose, show }: Props) {
  /// 步骤 1=> 选择条数 2=> 支付二维码 3=> 充值结果
  const [step, setStep] = useState(1);
  //------------------------------步骤1-----------------------------------------
  /// 选择的条数
  const [select, setSelect] = useState(rechargeItems[0]);
  //------------------------------步骤2-----------------------------------------
  const [payUrl, setPayUrl] = useState('');
  const timeRef = useRef<{ timer?: NodeJS.Timeout }>({});
  //-----------------------------步骤3-----------------------------------------
  const [payStatus, setPayStatus] = useState('');

  useEffect(() => {
    return stopLoop;
  }, []);

  async function handleCreatePay() {
    LoadingMask.show('正在生成订单...');
    try {
      let res = await apiCreatePay(select);
      let data = res.data;
      if (data.code === 200) {
        setPayUrl(data.data.payUrl);
        setStep(2);
        startLoop(data.data.orderSn);
      } else {
        Message.warning(data.msg ?? '生成失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '生成失败');
    } finally {
      LoadingMask.hide();
    }
  }

  function stopLoop() {
    clearInterval(timeRef.current.timer);
    timeRef.current.timer = undefined;
  }

  function startLoop(id: string | number) {
    if (timeRef.current.timer) {
      clearInterval(timeRef.current.timer);
    }
    timeRef.current.timer = setInterval(async () => {
      try {
        let res = await apiQueryPayStatus(id);
        let data = res.data;
        if (data.code === 200) {
          if (data.data !== payWait) {
            stopLoop();
            setPayStatus(data.data);
            setStep(3);
          }
        }
      } catch (e: any) {}
    }, 2000);
  }

  // @ts-ignore
  return (
    <DetailModal
      title="充值金额"
      contentClassName="pt-0 pr-0 h-300"
      show={show}
      onCancel={onClose}
      cancelBtnShow={false}
      confirmBtnShow={false}
    >
      {step === 1 && (
        <div>
          <div className="d-flex-r flex-wrap pl-10 pt-10">
            {rechargeItems.map((item) => (
              <div
                key={item}
                onClick={() => {
                  setSelect(item);
                }}
                className={`mr-10 mb-10 w-140 border p-10 border-radius-8 cursor-pointer text-center d-flex-r jc-center ai-center font-widget-600 h-60 ${
                  item === select ? 'border-arcoblue-color' : ''
                }`}
              >
                {item}元
              </div>
            ))}
          </div>
          <div className="ml-10 mt-20 font-12 text-9-color">
            说明：充值的款项只可用于本系统消费，且系统只支持原路退回至付款账号。
          </div>
          <div className="d-flex-r jc-end mt-30">
            <Button className="mr-20" onClick={() => onClose(false)}>
              取消
            </Button>
            <Button type="primary" onClick={handleCreatePay}>
              下一步
            </Button>
          </div>
        </div>
      )}
      {step === 2 && (
        <div className="bw-100">
          <div className="font-16 font-widget-600 text-center mb-30">微信扫码支付{select}元</div>
          <div className="d-flex-c ai-center">
            <QRCodeImg width={200} content={payUrl} />
          </div>
        </div>
      )}
      {step === 3 && (
        <div className="bw-100 bh-100">
          {payStatus === paySuccess && (
            <div>
              <Result
                status="success"
                title="支付成功"
                subTitle="账户充值成功,请关闭后刷新查看"
                extra={[
                  <Button type="primary" onClick={() => onClose(false)}>
                    关闭
                  </Button>,
                ]}
              ></Result>
            </div>
          )}
          {payStatus === payError && (
            <div>
              <Result
                status="error"
                title="支付失败"
                subTitle="支付失败,请联系管理员处理"
                extra={[
                  <Button type="primary" onClick={() => onClose(false)}>
                    关闭
                  </Button>,
                ]}
              ></Result>
            </div>
          )}
          {payStatus === payTimeOut && (
            <div>
              <Result
                status="warning"
                title="支付超时"
                subTitle="支付超时,支付超时已关闭，请重新下单支付"
                extra={<Button type="primary">关闭</Button>}
              ></Result>
            </div>
          )}
        </div>
      )}
    </DetailModal>
  );
}
